<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="在Alibaba Sentinel 限流与熔断初探(技巧篇) 的示例中我选择了 sentinel-demo-apache-dubbo 作为突破点，故本文就从该项目入手，看看 Sentinel 是如何对 Dubbo 做的适配，让项目使用方无感知，只需要引入对应的依即可。 sentinel-apache-dubbo-adapter 比较简单，展开如下：上面的代码应该比较简单，在正式进入源码研究之前，我">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析 Sentinel 之 Dubbo适配原理">
<meta property="og:url" content="https://www.codingw.net/posts/2496ec4.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="在Alibaba Sentinel 限流与熔断初探(技巧篇) 的示例中我选择了 sentinel-demo-apache-dubbo 作为突破点，故本文就从该项目入手，看看 Sentinel 是如何对 Dubbo 做的适配，让项目使用方无感知，只需要引入对应的依即可。 sentinel-apache-dubbo-adapter 比较简单，展开如下：上面的代码应该比较简单，在正式进入源码研究之前，我">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20191222163854410.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2019122216430790.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2020-10-15T14:39:35.000Z">
<meta property="article:modified_time" content="2021-04-26T12:08:45.355Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20191222163854410.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/2496ec4.html"/>





  <title>源码分析 Sentinel 之 Dubbo适配原理 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/2496ec4.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析 Sentinel 之 Dubbo适配原理</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-10-15T22:39:35+08:00">
                2020-10-15
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/sentinel/" itemprop="url" rel="index">
                    <span itemprop="name">sentinel</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/2496ec4.html" class="leancloud_visitors" data-flag-title="源码分析 Sentinel 之 Dubbo适配原理">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>在<a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/103544443">Alibaba Sentinel 限流与熔断初探(技巧篇)</a> 的示例中我选择了 sentinel-demo-apache-dubbo 作为突破点，故本文就从该项目入手，看看 Sentinel 是如何对 Dubbo 做的适配，让项目使用方无感知，只需要引入对应的依即可。</p>
<p>sentinel-apache-dubbo-adapter 比较简单，展开如下：<br><img src="https://img-blog.csdnimg.cn/20191222163854410.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>上面的代码应该比较简单，在正式进入源码研究之前，我先抛出如下二个问题：</p>
<ul>
<li>1、限流、熔断相关的功能是在 Dubbo 的客户端实现还是服务端实现？为什么？</li>
<li>2、如何对 Dubbo 进行功能扩展而无需改动业务代码？</li>
</ul>
<p>Dubbo 提供了 Filter 机制对功能进行无缝扩展，有关 Dubbo Filter 机制，大家可以查阅笔者的源码研究 Dubbo 系列：<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/uv7ev-D-9wo3Oct3NCcKTQ">Dubbo Filter机制概述</a>。</p>
<p>接下来我们带着上面的问题1开始本章的研究。</p>
<h2 id="1、源码分析-SentinelDubboConsumerFilter"><a href="#1、源码分析-SentinelDubboConsumerFilter" class="headerlink" title="1、源码分析 SentinelDubboConsumerFilter"></a>1、源码分析 SentinelDubboConsumerFilter</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Activate(group = &quot;consumer&quot;)</span>   <span class="comment">// @1</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SentinelDubboConsumerFilter</span> <span class="keyword">implements</span> <span class="title">Filter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SentinelDubboConsumerFilter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        RecordLog.info(<span class="string">&quot;Sentinel Apache Dubbo consumer filter initialized&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Result <span class="title">invoke</span><span class="params">(Invoker&lt;?&gt; invoker, Invocation invocation)</span> <span class="keyword">throws</span> RpcException </span>&#123;</span><br><span class="line">        Entry interfaceEntry = <span class="keyword">null</span>;</span><br><span class="line">        Entry methodEntry = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            String resourceName = DubboUtils.getResourceName(invoker, invocation, DubboConfig.getDubboConsumerPrefix());   <span class="comment">// @2</span></span><br><span class="line">            interfaceEntry = SphU.entry(invoker.getInterface().getName(),</span><br><span class="line">                ResourceTypeConstants.COMMON_RPC, EntryType.OUT);     <span class="comment">// @3</span></span><br><span class="line">            methodEntry = SphU.entry(resourceName, ResourceTypeConstants.COMMON_RPC, EntryType.OUT);    <span class="comment">// @4</span></span><br><span class="line"></span><br><span class="line">            Result result = invoker.invoke(invocation);            <span class="comment">// @5</span></span><br><span class="line">            <span class="keyword">if</span> (result.hasException()) &#123;                                     <span class="comment">// @6</span></span><br><span class="line">                Throwable e = result.getException();</span><br><span class="line">                <span class="comment">// Record common exception.</span></span><br><span class="line">                Tracer.traceEntry(e, interfaceEntry);</span><br><span class="line">                Tracer.traceEntry(e, methodEntry);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> result;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (BlockException e) &#123;        </span><br><span class="line">            <span class="keyword">return</span> DubboFallbackRegistry.getConsumerFallback().handle(invoker, invocation, e);  <span class="comment">// @7</span></span><br><span class="line">        &#125; <span class="keyword">catch</span> (RpcException e) &#123;    </span><br><span class="line">            Tracer.traceEntry(e, interfaceEntry);</span><br><span class="line">            Tracer.traceEntry(e, methodEntry);</span><br><span class="line">            <span class="keyword">throw</span> e;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (methodEntry != <span class="keyword">null</span>) &#123;   <span class="comment">// @8</span></span><br><span class="line">                methodEntry.exit();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (interfaceEntry != <span class="keyword">null</span>) &#123;</span><br><span class="line">                interfaceEntry.exit();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：通过 @Activate 注解定义该 Filter 在客户端生效。</p>
<p>代码@2：在 Sentinel 中一个非常核心的概念就是资源，即要定义限流的目标，当出现什么异常（匹配用户配置的规则）对什么进行熔断操作，Dubbo 服务中的资源通常是 Dubbo 服务，分为服务接口级或方法级，故该方法返回 Dubbo 的资源名，其主要实现特征如下：</p>
<ul>
<li>如果启用用户定义资源的前缀，默认为 false ，可以通过配置属性：csp.sentinel.dubbo.resource.use.prefix 来定义是否需要启用前缀。如果启用前缀，消费端的默认前缀为 dubbo:consumer:，可以通过配置属性 csp.sentinel.dubbo.resource.consumer.prefix 来自定义消费端的资源前缀。</li>
<li>Dubbo 资源的名称表示方法为：interfaceName + “:” + methodName + “(“ + “paramTyp1参数列表，多个用 , 隔开” + “)”。</li>
</ul>
<p>代码@3：调用 Sentinel 核心API  SphU.entry 进入 Dubbo InterfaceName。从方法的名称我们也能很容易的理解，就是使用 Sentienl API 进入资源名为 Dubbo 接口提供者类全路径限定名，即认为调用该方法，Sentienl 会收集该资源的调用信息，然后Sentinel 根据运行时收集的信息，再配合限流规则，熔断等规则进行计算是否需要限流或熔断。本节我们不打算深入研究 SphU 的核心方法研究，先初步了解该方法：</p>
<ul>
<li><p>String name 资源的名称。</p>
</li>
<li><p>int resourceType 资源的类型，在 Sentinel 中目前定义了 如下五中资源：</p>
<ul>
<li>ResourceTypeConstants.COMMON<br>同样类型。</li>
<li>ResourceTypeConstants.COMMON_WEB<br>WEB 类资源。</li>
<li>ResourceTypeConstants.COMMON_RPC<br>RPC 类型。</li>
<li>ResourceTypeConstants.COMMON_API_GATEWAY<br>接口网关。</li>
<li>ResourceTypeConstants.COMMON_DB_SQL<br>数据库 SQL 语句。</li>
</ul>
</li>
<li><p>EntryType type<br>进入资源的方式，主要分为 EntryType.OUT、EntryType.IN，只有 EntryType.IN 方式才能对资源进行阻塞。</p>
</li>
</ul>
<p>代码@4：调用 Sentinel 核心API SphU.entry 进入 Dubbo method 级别。</p>
<p>代码@5：调用 Dubbo 服务提供者方法。</p>
<p>代码@6：如果出现调用异常，可以通过 Sentinel 的 Tracer.traceEntry 跟踪本次调用资源进入的情况，详细 API 将在该系列的后续文章中详细介绍。</p>
<p>代码@7：如果是由于触发了限流、熔断等操作，抛出了阻塞异常，可通过 注册 ConsumerFallback 来实现消费者快速失败，将在下文详细介绍。</p>
<p>代码@8： SphU.entry 与 资源的 exit 方法需要成对出现，否则会出现统计错误。</p>
<span id="more"></span>

<h2 id="2、源码分析-SentienlDubboProviderFilters"><a href="#2、源码分析-SentienlDubboProviderFilters" class="headerlink" title="2、源码分析 SentienlDubboProviderFilters"></a>2、源码分析 SentienlDubboProviderFilters</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Activate(group = &quot;provider&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SentinelDubboProviderFilter</span> <span class="keyword">implements</span> <span class="title">Filter</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SentinelDubboProviderFilter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        RecordLog.info(<span class="string">&quot;Sentinel Apache Dubbo provider filter initialized&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Result <span class="title">invoke</span><span class="params">(Invoker&lt;?&gt; invoker, Invocation invocation)</span> <span class="keyword">throws</span> RpcException </span>&#123;</span><br><span class="line">        <span class="comment">// Get origin caller.</span></span><br><span class="line">        String application = DubboUtils.getApplication(invocation, <span class="string">&quot;&quot;</span>);</span><br><span class="line">        Entry interfaceEntry = <span class="keyword">null</span>;</span><br><span class="line">        Entry methodEntry = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            String resourceName = DubboUtils.getResourceName(invoker, invocation, DubboConfig.getDubboProviderPrefix());   <span class="comment">// @1</span></span><br><span class="line">            String interfaceName = invoker.getInterface().getName();</span><br><span class="line">            <span class="comment">// Only need to create entrance context at provider side, as context will take effect</span></span><br><span class="line">            <span class="comment">// at entrance of invocation chain only (for inbound traffic).</span></span><br><span class="line">            ContextUtil.enter(resourceName, application);</span><br><span class="line">            interfaceEntry = SphU.entry(interfaceName, ResourceTypeConstants.COMMON_RPC, EntryType.IN);  <span class="comment">// @2</span></span><br><span class="line">            methodEntry = SphU.entry(resourceName, ResourceTypeConstants.COMMON_RPC,</span><br><span class="line">                EntryType.IN, invocation.getArguments());</span><br><span class="line">            Result result = invoker.invoke(invocation);</span><br><span class="line">            <span class="keyword">if</span> (result.hasException()) &#123;</span><br><span class="line">                Throwable e = result.getException();</span><br><span class="line">                <span class="comment">// Record common exception.</span></span><br><span class="line">                Tracer.traceEntry(e, interfaceEntry);</span><br><span class="line">                Tracer.traceEntry(e, methodEntry);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> result;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (BlockException e) &#123; </span><br><span class="line">            <span class="keyword">return</span> DubboFallbackRegistry.getProviderFallback().handle(invoker, invocation, e);   <span class="comment">// @3</span></span><br><span class="line">        &#125; <span class="keyword">catch</span> (RpcException e) &#123;</span><br><span class="line">            Tracer.traceEntry(e, interfaceEntry);</span><br><span class="line">            Tracer.traceEntry(e, methodEntry);</span><br><span class="line">            <span class="keyword">throw</span> e;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (methodEntry != <span class="keyword">null</span>) &#123;</span><br><span class="line">                methodEntry.exit(<span class="number">1</span>, invocation.getArguments());</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (interfaceEntry != <span class="keyword">null</span>) &#123;</span><br><span class="line">                interfaceEntry.exit();</span><br><span class="line">            &#125;</span><br><span class="line">            ContextUtil.exit();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Dubbo 服务提供者与消费端的适配套路差不多，这里就重点阐述一下其不同点。<br>代码@1：如果启用前缀，默认服务提供者的资源会加上前缀：dubbo:provider:，可以通过在配置文件中配置属性 csp.sentinel.dubbo.resource.provider.prefix 改变其默认值。</p>
<p>代码@2：服务端调用 SphU.entry 时其进入类型为 EntryType.IN。</p>
<p>代码@3：同样可以在 抛出阻塞异常(BlockException) 时指定快速失败回调处理逻辑。</p>
<h2 id="3、Sentienl-Dubbo-FallBack-机制"><a href="#3、Sentienl-Dubbo-FallBack-机制" class="headerlink" title="3、Sentienl Dubbo FallBack 机制"></a>3、Sentienl Dubbo FallBack 机制</h2><p>Sentinel Dubbo FallBack 机制比较简单，就是提供一个全局的 FallBack 回调，可以分别为服务提供端，服务消费端指定。只需实现 DubboFallback 接口，其声明如下：<br><img src="https://img-blog.csdnimg.cn/2019122216430790.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>然后需要调用 DubboFallbackRegistry 的 setConsumerFallback 和 setProviderFallback 方法分别注册消费端，服务端相关的监听器。通常只需要在启动应用的时候，将其进行注册即可。</p>
<h2 id="4、总结"><a href="#4、总结" class="headerlink" title="4、总结"></a>4、总结</h2><p>本文只是以 Sentienl 对 Dubbo 的适配实现来了解 Sentinel 核心相关的 API，其核心实现就是利用 Dubbo 的 Filter 机制进行无缝的过滤拦截。但本文只是提到 Sentinel 如下核心方法：</p>
<ul>
<li>SphU.entry</li>
<li>Entry.exit</li>
<li>Tracer.traceEntry</li>
</ul>
<p>上述这些方法，将在后面的文章中进行深入探究，即从下一篇文章开始，我们将真正进入 Sentinel 的世界中，让我们一探究竟限流、熔断通常是如何实现的。</p>
<p>本文就介绍到这里了，点赞是一种美德，您的点赞是我持续分享的最大动力，谢谢。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/18c7756d.html" rel="next" title="源码分析Mybatis MappedStatement的创建流程">
                <i class="fa fa-chevron-left"></i> 源码分析Mybatis MappedStatement的创建流程
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/45a744cd.html" rel="prev" title="源码分析 Sentinel DegradeSlot 熔断实现原理">
                源码分析 Sentinel DegradeSlot 熔断实现原理 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90-SentinelDubboConsumerFilter"><span class="nav-number">1.</span> <span class="nav-text">1、源码分析 SentinelDubboConsumerFilter</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90-SentienlDubboProviderFilters"><span class="nav-number">2.</span> <span class="nav-text">2、源码分析 SentienlDubboProviderFilters</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3%E3%80%81Sentienl-Dubbo-FallBack-%E6%9C%BA%E5%88%B6"><span class="nav-number">3.</span> <span class="nav-text">3、Sentienl Dubbo FallBack 机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4%E3%80%81%E6%80%BB%E7%BB%93"><span class="nav-number">4.</span> <span class="nav-text">4、总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
